defmodule PhoenixChina.SessionController do
  use PhoenixChina.Web, :controller

  import Comeonin.Bcrypt, only: [checkpw: 2]

  alias PhoenixChina.User

  plug :scrub_params, "user" when action in [:create]

  def new(conn, _params) do
	render conn, "new.html", changeset: User.changeset(%User{})  	
  end

  def create(conn,%{"user"=>%{"name" => name,"password" => password}}) when not is_nil(name) and not is_nil(password) do
  	user = Repo.get_by(User, name: name)
  	sign_in(user, password, conn)
  end

  def create(conn, _) do
  	failed_login(conn, "用户名密码错误!")
  end

  def delete(conn, _params) do
  	conn
  	|> delete_session(:current_user)
  	|> put_flash(:info, "退出成功!")
  	|> redirect(to: page_path(conn, :index))
  end

  defp sign_in(user, _password, conn) do
  	if checkpw(_password, user.password_digest) do
  	  conn
  	  |> put_session(:current_user,%{id: user.id,name: user.name})
  	  |> put_flash(:info, "登录成功!")
  	  |> redirect(to: page_path(conn, :index))
  	else
  	  failed_login(conn, "用户名密码错误!")
  	end
  end

  defp failed_login(conn, message) do
  	conn
  	|> put_session(:current_user, nil)
  	|> put_flash(:error, message)
  	|> redirect(to: page_path(conn, :index))
  	|> halt()
  end

end
